<?php

namespace app\services;

use Overtrue\EasySms\EasySms;
use support\Cache;
use Webman\Config;

class SmsService
{
    const CHANGE_PAY_PASSWORD = 'change_pay_password';

    const CHANGE_PHONE = 'change_phone';

    const REGISTER = 'register';

    const LOGIN = 'login';

    const FIND_PASSWORD = 'find_password';

    public static function send($mobile, $scene)
    {
//        if (getenv('APP_DEBUG') == 1) {
//            $code = 123456;
//        } else {
            $code = mt_rand(100000, 999999);

            try {
                $smsConfig = ConfigService::getByGroup('sms');
                $config = ConfigService::getSmsConfig();
                $easySms = new EasySms($config);
                $easySms->send($mobile, [
                    'content'  => str_replace('######', $code, $smsConfig['sms_aliyun_template']),
                    'template' => $smsConfig['sms_template'],
                    'data' => [
                        'code' => $code
                    ],
                ]);
            } catch (\Exception $e) {
                echo $e->getTraceAsString();
                throw $e;
            }
//        }

        Cache::set('sms-' . $mobile . $scene, $code);
    }

    public static function check($mobile, $scene, $code)
    {
        $key = 'sms-' . $mobile . $scene;
        if ($code != Cache::get($key)) {
            throw new \Exception('验证码不正确');
        }

        Cache::delete($key);
    }
}